package org.nanotek.mq.receive;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.nanotek.cms.domain.message.BodyMessageContainer;
import org.nanotek.mq.ReceiverService;
import org.nanotek.util.Base;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BaseMessageListener implements MessageListener {

	@Autowired
	private ReceiverService receiverService;

	public BaseMessageListener() {
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	}

	@Override
	public void onMessage(Message arg0) {
		ObjectMessage message = (ObjectMessage) arg0;
		BodyMessageContainer messageContainer = null;
		try {
			messageContainer = (BodyMessageContainer)message.getObject();
			if (receiverService !=null)
				receiverService.processMessage (messageContainer.getMessageType(), messageContainer.getBodyMessage());
			else {
				Base<?> base = messageContainer.getBodyMessage();
				System.out.println("MESSAGE TYPE " + messageContainer.getMessageType());
				if (base !=null) {
					System.out.println("BASE TYPE " + base.getClass().getSimpleName());
					System.out.println("BASE ID " + base.getId());
				}
			}
		} catch (JMSException e) {
			throw new RuntimeException(e);
		}
	}

	public ReceiverService getReceiverService() {
		return receiverService;
	}

	public void setReceiverService(ReceiverService receiverService) {
		this.receiverService = receiverService;
	}

}
